package com.utilsapi.CountTime;

import android.os.Handler;
import android.os.Message;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @anthor liuwenwang
 * QQ:2653256624
 * @time 2017/11/27 13:15
 */
public class TimeUtils {
    private  long startTime=0;
    private  long endTime=0;
    private  int periaTime=1000;//毫秒
    private  boolean isCounting;
    private  int type;//0的格式为：hh:mm:ss 1的格式为：mm:ss 2的格式为：mm:ss:SSS
    private  DateFormat formatter;
    private  Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String date="";
            endTime=System.currentTimeMillis()-startTime;
            switch (msg.what){
                case 0:
                    if(formatter==null){
                        formatter= new SimpleDateFormat("mm:ss");
                    }

                    int horse = ((int) (endTime))/ (1000 * 60 * 60);
                    String da = formatter.format(endTime);
                    if(horse<10){
                        date="0"+horse+":"+da;
                    }else {
                        date = horse + ":" + da;
                    }
                    break;
                case 1:
                    if(formatter==null){
                        formatter= new SimpleDateFormat("mm:ss");
                    }
                case 2:
                    if(formatter==null){
                        formatter= new SimpleDateFormat("mm:ss:SSS");
                    }
                    date = formatter.format(endTime);
                    break;
            }
            if(mListener!=null)mListener.showTime(type,date);
        }
    };
    public  void initTime(final int format,TimeListener listener){
        mListener=listener;
        isCounting=true;
         startTime=System.currentTimeMillis();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if(isCounting){
                      type=format;
                    if(type==0||type==1){
                        periaTime=1000;
                    }else if(type==2)periaTime=1;
                    if(format<0||format>2)
                        throw new RuntimeException("格式不正确");
                    mHandler.sendEmptyMessage(type);
                }else{
                    cancel();
                }
            }
        },0,periaTime);
    }
public void stopTime(){
    isCounting=false;
    mListener=null;
}
     TimeListener mListener;
    public  interface TimeListener{
      void showTime(int type,String time);
    }
}
